<template>
  <!-- 通知管理 -->
  <div class="notice-manage">
    <div class="search-container">
      <el-form ref="ruleFormRef" :model="queryParams.entity" label-width="80" inline>
        <el-form-item label="关键字" prop="title">
          <el-input v-model="queryParams.entity.title" maxlength="60" placeholder="通知标题" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="publishStatus">
          <el-select v-model="queryParams.entity.publishStatus" placeholder="全部" style="width: 100px;" clearable>
            <el-option v-for="(item, index) in PUBLISH_TYPE" :value="item.value" :label="item.label" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="rangeTime">
          <el-date-picker v-model="queryParams.entity.rangeTime" type="daterange" start-placeholder="开始时间"
            end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 260px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" icon="Plus" @click="handleLinkEdit('edit', {})">
          新增
        </el-button>
      </template>
      <el-table v-loading="loading" :data="tableData" highlight-current-row border>
        <el-table-column type="index" label="序号" :width="60" align="left" />
        <el-table-column v-for="(item, index) in columnData" :key="index" :prop="item.prop" :label="item.label"
          min-width="120" :width="item.width || ''" :fixed="item.fixed || false" show-overflow-tooltip
          :resizable="false">
          <template #default="{ row }">
            <span v-if="['type'].includes(item.prop)">
              {{ getDictOpt(dictOptions['notice_type'], row[item.prop]).label }}
            </span>
            <span v-else-if="['level'].includes(item.prop)">
              <el-tag :type="getDictOpt(dictOptions['public_level'], row[item.prop]).tagType"> {{
                getDictOpt(dictOptions['public_level'], row[item.prop]).label }}</el-tag>
            </span>
            <span v-else-if="['publishStatus'].includes(item.prop)">
              <el-tag :type="getDictOpt(PUBLISH_TYPE, row[item.prop]).tagType"> {{
                getDictOpt(PUBLISH_TYPE, row[item.prop]).label }}</el-tag>
            </span>
            <span v-else>{{ row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="280">
          <template #default="scope">
            <el-button type="primary" icon="View" link @click="handleLinkEdit('view', scope.row)">
              查看
            </el-button>
            <el-button type="primary" icon="Edit" link @click="handleLinkEdit('edit', scope.row)"
              v-if="[0, -1].includes(scope.row.publishStatus)">
              编辑
            </el-button>
            <el-button type="primary" icon="Upload" link @click="handlePublish(scope.row)"
              v-if="[0, -1].includes(scope.row.publishStatus)">
              发布
            </el-button>
            <el-button type="warning" icon="SortDown" link @click="handleRevoke(scope.row)"
              v-if="[1].includes(scope.row.publishStatus)">
              撤回
            </el-button>
            <el-button type="danger" icon="Delete" link @click="handleDelete(scope.row)"
              v-if="[0, -1].includes(scope.row.publishStatus)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>
  </div>
</template>

<script setup>
defineOptions({ name: 'NoticeManage' })
import { onMounted, reactive, ref, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { format, addDays } from 'date-fns'
import Pagination from '@/components/Pagination.vue'
import { getDictOpt } from '@/utils/common'
import { getNoticePage, publishNotice, revokeNotice, deltetNotice } from '@views/noticeManage/api/noticeManage'
import { PUBLISH_TYPE } from '@constants/dictionary'
const { proxy } = getCurrentInstance()
const dictOptions = ref(proxy.useDict('notice_type', 'public_level'))

const router = useRouter()
const loading = ref(false)
const queryParams = reactive({ entity: { title: '', publishStatus: '', rangeTime: [format(addDays(new Date(), -7), 'yyyy-MM-dd'), format(new Date(), 'yyyy-MM-dd')] }, pageNo: 1, pageSize: 10 })
const total = ref(0)
const columnData = ref([
  {
    label: '通知标题',
    prop: 'title'
  },
  {
    label: '通知类型',
    prop: 'type'
  },
  {
    label: '发布人',
    prop: 'publisherId'
  },
  {
    label: '发布时间',
    prop: 'publishTime',
    width: 180
  },
  {
    label: '等级',
    prop: 'level',
    width: 100
  },
  {
    label: '状态',
    prop: 'publishStatus',
    width: 100
  }
])
const tableData = ref()
const ruleFormRef = ref(null)

// 获取数据
const handleQuery = async () => {
  loading.value = true
  let _queryParams = JSON.parse(JSON.stringify(queryParams))
  _queryParams.entity.startTime = _queryParams.entity.rangeTime ? _queryParams.entity.rangeTime[0] + ' 00:00:00' : ''
  _queryParams.entity.endTime = _queryParams.entity.rangeTime ? _queryParams.entity.rangeTime[1] + ' 23:59:59' : ''
  delete _queryParams.entity.rangeTime

  const res = await getNoticePage(_queryParams)
  loading.value = false
  if (res?.code === 200) {
    tableData.value = res.data.records || []
    total.value = res.total || 0
  }
}

// 重置表单
const handleResetQuery = () => {
  ruleFormRef.value.resetFields()
  queryParams.pageNo = 1
  handleQuery()
}

// 打开新增/详情弹窗
const handleLinkEdit = (type, row) => {
  router.push({ path: '/setting/notice-edit', query: { id: row.id, type: type }})
}

// 发布
const handlePublish = (row) => {
  ElMessageBox.confirm('确认发布的数据项', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      let res = await publishNotice({ id: row.id })
      if (res?.code === 200) {
        ElMessage.success('发布成功')
        handleQuery()
      }
    })
    .catch(() => { })
}

// 撤回
const handleRevoke = (row) => {
  ElMessageBox.confirm('确认撤回的数据项', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      let res = await revokeNotice({ id: row.id })
      if (res?.code === 200) {
        ElMessage.success('撤回成功')
        handleQuery()
      }
    })
    .catch(() => { })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除的数据项', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      let res = await deltetNotice({ id: row.id })
      if (res?.code === 200) {
        ElMessage.success('删除成功')
        handleQuery()
      }
    })
    .catch(() => { })
}

// 初始化
onMounted(() => {
  handleQuery()
})
</script>

<style scoped lang="scss"></style>
